package com.winit.schedule.job.tracker.web.controller;

import com.alibaba.fastjson.JSON;
import com.winit.schedule.core.model.JobID;
import com.winit.schedule.core.repository.entity.Page;
import com.winit.schedule.core.repository.entity.TaskEntity;
import com.winit.schedule.core.repository.entity.UserEntity;
import com.winit.schedule.core.repository.query.UserQuery;
import com.winit.schedule.core.zk.ZKService;
import com.winit.schedule.job.tracker.JobTrackerContext;
import com.winit.schedule.job.tracker.repository.ConsoleDataManager;
import com.winit.schedule.job.tracker.util.Constants;
import com.winit.schedule.job.tracker.util.Md5Encrypt;
import com.winit.schedule.job.tracker.web.auth.User;
import com.winit.schedule.webc.annotation.Controller;
import com.winit.schedule.webc.annotation.RequestMapping;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * Created by jianke.zhang on 2017/5/3.
 */
@Controller(UserController.NAMESPACE)
public class UserController extends BaseController{

    public static final String NAMESPACE = "user";

    private static Logger logger = LoggerFactory.getLogger(OpenController.class);

    private static UserController instance = null;

    private ConsoleDataManager consoleDataManager;

    private JobTrackerContext jobTrackerContext;

    private UserController(JobTrackerContext jobTrackerContext){
        this.jobTrackerContext = jobTrackerContext;
        this.consoleDataManager = jobTrackerContext.getConsoleDataManager();
    }

    public static synchronized UserController getInstance(JobTrackerContext context) {
        if (null == instance) {
            instance = new UserController(context);
        }
        return instance;
    }

    @RequestMapping("users")
    public Page queryUsers(HttpServletRequest req, HttpServletResponse resp) {

        int page = Integer.parseInt(req.getParameter("page"));
        int rows = Integer.parseInt(req.getParameter("rows"));
        String username = req.getParameter("username");
        String admin = req.getParameter("admin");
        String disabled = req.getParameter("disabled");
        long startTime = 0;
        long endTime = 0;
        UserQuery query = new UserQuery();
//        query.setAdmin(false);
        query.setUsername(username);
        if (StringUtils.isNotBlank(disabled)) {
            query.setDisabled(Boolean.valueOf(disabled));
        }
        if (StringUtils.isNotBlank(admin)) {
            query.setAdmin(Boolean.valueOf(admin));
        }

        return consoleDataManager.queryUserPage(query, page, rows);
    }

    @RequestMapping("getUserByUsername")
    public UserEntity getUserByUsername(HttpServletRequest req, HttpServletResponse resp) {
        UserEntity userEntity = null;
        try {
            User sessionUser = (User) req.getSession().getAttribute(Constants.SESSION_USERINFO);
            if (null != sessionUser && sessionUser.isAdmin()) {
                String username = req.getParameter("username");
                userEntity = consoleDataManager.queryUserByUsername(username);
            }
        } catch (Exception e) {
            logger.error("Start job failure.", e);
            userEntity = new UserEntity();
        }
        return userEntity;
    }

    @RequestMapping("enableUser")
    public Object enableUser(HttpServletRequest req, HttpServletResponse resp) {
        String reMsg = "";
        try {
            User sessionUser = (User) req.getSession().getAttribute(Constants.SESSION_USERINFO);
            if (null != sessionUser && sessionUser.isAdmin()) {
                String username = req.getParameter("username");
                UserEntity userEntity = consoleDataManager.queryUserByUsername(username);
                userEntity.setDisabled(false);
                consoleDataManager.updateUser(userEntity);
            } else {
                reMsg = "没有操作权限";
            }
        } catch (Exception e) {
            logger.error("enable User failure.", e);
            reMsg = "系统异常.";
        }
        return buildMesssage(reMsg);
    }

    @RequestMapping("disableUser")
    public Object disableUser(HttpServletRequest req, HttpServletResponse resp) {
        String reMsg = "";
        try {
            User sessionUser = (User) req.getSession().getAttribute(Constants.SESSION_USERINFO);
            if (null != sessionUser && sessionUser.isAdmin()) {
                String username = req.getParameter("username");
                UserEntity userEntity = consoleDataManager.queryUserByUsername(username);
                userEntity.setDisabled(true);
                consoleDataManager.updateUser(userEntity);
            } else {
                reMsg = "没有操作权限";
            }
        } catch (Exception e) {
            logger.error("disabled User failure.", e);
            reMsg = "系统异常.";
        }
        return buildMesssage(reMsg);
    }

    @RequestMapping("updatePwd")
    public Object updatePwd(HttpServletRequest req, HttpServletResponse resp) {
        String userStr = req.getParameter("user");
        UserEntity user = JSON.parseObject(userStr, UserEntity.class);
        String reMsg = "";
        try {
            User sessionUser = (User) req.getSession().getAttribute(Constants.SESSION_USERINFO);
            if (null != sessionUser && sessionUser.isAdmin()) {
                consoleDataManager.updateUserPws(user.getUsername(), Md5Encrypt.md5(user.getPassword()));
            } else {
                reMsg = "没有操作权限";
            }
        } catch (Exception e) {
            logger.error("update user password fail..", e);
            reMsg = "系统异常.";
        }
        return buildMesssage(reMsg);
    }

    @RequestMapping("saveUser")
    public Object saveUser(HttpServletRequest req, HttpServletResponse resp) {
        String userStr = req.getParameter("user");
        UserEntity user = JSON.parseObject(userStr, UserEntity.class);
        String reMsg = "";
        try {
            User sessionUser = (User) req.getSession().getAttribute(Constants.SESSION_USERINFO);
            if (null != sessionUser && sessionUser.isAdmin()) {
                UserEntity oldUser = consoleDataManager.queryUserByUsername(user.getUsername());
                if (null == oldUser) {
                    user.setPassword(Md5Encrypt.md5(user.getPassword()));
                    user.setAddTime(new Date());
                    consoleDataManager.saveUser(user);
                } else {
                    reMsg = "用户已经存在.";
                }
            } else {
                reMsg = "没有操作权限";
            }

        } catch (Exception e) {
            logger.error("update user password fail..", e);
            reMsg = "系统异常.";
        }
        return buildMesssage(reMsg);
    }

    @RequestMapping("updateUser")
    public Object updateUser(HttpServletRequest req, HttpServletResponse resp) {
        String userStr = req.getParameter("user");
        UserEntity user = JSON.parseObject(userStr, UserEntity.class);
        String reMsg = "";
        try {
            User sessionUser = (User) req.getSession().getAttribute(Constants.SESSION_USERINFO);
            if (null != sessionUser && sessionUser.isAdmin()) {
                UserEntity oldUser = consoleDataManager.queryUserByUsername(user.getUsername());
                if (null != oldUser) {
                    oldUser.setAdmin(user.isAdmin());
                    oldUser.setDisabled(user.isDisabled());
                    oldUser.setRemark(user.getRemark());
                    oldUser.setUpdateTime(new Date());
                    consoleDataManager.updateUser(oldUser);
                } else {
                    reMsg = "用户不存在.";
                }
            } else {
                reMsg = "没有操作权限";
            }

        } catch (Exception e) {
            logger.error("update user fail..", e);
            reMsg = "系统异常.";
        }
        return buildMesssage(reMsg);
    }

    @RequestMapping("updatePwdBySelf")
    public Object updatePwdBySelf(HttpServletRequest req, HttpServletResponse resp) {
        String oldPassword = req.getParameter("oldPassword");
        String password = req.getParameter("password");
        String reMsg = "";
        try {
            User sessionUser = (User) req.getSession().getAttribute(Constants.SESSION_USERINFO);
            if (null != sessionUser) {
                UserEntity oldUser = consoleDataManager.findByUsernameAndPassword(sessionUser.getUsername(), Md5Encrypt.md5(oldPassword));
                if (null != oldUser) {
                    consoleDataManager.updateUserPws(sessionUser.getUsername(), Md5Encrypt.md5(password));
                } else {
                    reMsg = "原密码输入错误，请重新输入";
                }
            } else {
                reMsg = "没有操作权限";
            }
        } catch (Exception e) {
            logger.error("update user password fail..", e);
            reMsg = "系统异常.";
        }
        return buildMesssage(reMsg);
    }

    @RequestMapping("getLoginUser")
    public UserEntity getLoginUser(HttpServletRequest req, HttpServletResponse resp) {
        User sessionUser = null;
        try {
            sessionUser = (User) req.getSession().getAttribute(Constants.SESSION_USERINFO);
        } catch (Exception e) {
            logger.error("Start job failure.", e);
            sessionUser = new User();
        }
        return sessionUser;
    }

}
